package br.ufpb.di.knowledgetv.sqtv.services;

import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDFS;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * User: manoel
 * Date: 01/08/13
 */
@Component
public class FreebaseService extends AbstractService {

    private static final HttpRequestFactory REQUEST_FACTORY = new NetHttpTransport().createRequestFactory();
    private static final JSONParser JSON_PARSER = new JSONParser();
    private static final String KEY = "AIzaSyBi4zLjqQeZHfOeKdzGBZpsNARrVHJmKkk";


    @Override
    public List<Resource> searchByKeyword(String keyword) {
        List<Resource> resourceList = new ArrayList<Resource>();
        Model model = ModelFactory.createDefaultModel();
        try {
            GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
            url.put("query", keyword);
            url.put("filter", "(all domain:/film) (all domain:/tv)");
            url.put("limit", "10");
            url.put("indent", "true");
            url.put("key", KEY);
            HttpRequest httpRequest = REQUEST_FACTORY.buildGetRequest(url);
            HttpResponse httpResponse = httpRequest.execute();
            JSONObject response = (JSONObject) JSON_PARSER.parse(httpResponse.parseAsString());
            JSONArray results = (JSONArray) response.get("result");
            for (Object resultObject : results) {
                JSONObject result = (JSONObject) resultObject;
                String topicId = (String) result.get("mid");
                topicId = topicId.substring(1).replace('/', '.');
                String uri = String.format("http://rdf.freebase.com/ns/%s", topicId);
                Resource resource = model.createResource(uri);
                resource.addProperty(RDFS.label, (String) result.get("name"));
                resource.addProperty(RDFS.domain, this.beanName);
                resourceList.add(resource);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resourceList;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public Model getModel(String url) {
        Model model = ModelFactory.createDefaultModel();
        try {
            GenericUrl url1 = new GenericUrl(url);
            HttpRequest httpRequest = REQUEST_FACTORY.buildGetRequest(url1);
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept("application/rdf+xml");
            httpRequest.setHeaders(headers);
            HttpResponse response = httpRequest.execute();
            model.read(response.getContent(), null);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

}
